<!--
 * @author  dumeng
 新建/编辑试题
-->
<template>
  <div class="question-manage">
    <div class="main-title">新建/编辑试题</div>
    <el-card v-if="anliContent" class="box-card">
      <div ref="anlicontent" class="anlicontent" :class="[isShowMoreBtn && !showMore && 'etc']">
        <span class="title">案例内容：</span>{{ anliContent }}
      </div>
      <span v-if="isShowMoreBtn" class="show-more-btn" @click="showMore = !showMore">{{ showMore ? '收起' : '展开' }} <i
        :class="[!showMore ? 'el-icon-caret-bottom' : 'el-icon-caret-top']"
      /></span>
    </el-card>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      class="dataForm"
      label-position="right"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="试题类型" prop="type">
            <el-select
              v-model="form.type"
              :disabled="state === 'update'"
              placeholder="请选择分类"
              clearable
              :style="{width:'100%'}"
            >
              <el-option
                v-for="(item, index) in dict.STLX"
                :key="index"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template v-if="state === 'update' && data.id">
      <danxuan v-if="form.type == 10" ref="danxuan" :type="form.type" :get-data="data" />
      <duoxuan v-else-if="form.type == 20" ref="duoxuan" :type="form.type" :get-data="data" />
      <panduan v-else-if="form.type == 30" ref="panduan" :type="form.type" :get-data="data" />
      <tiankong v-else-if="form.type == 40" ref="tiankong" :type="form.type" :get-data="data" />
    </template>
    <template v-if="state === 'create'">
      <danxuan v-if="form.type == 10" ref="danxuan" :type="form.type" />
      <duoxuan v-else-if="form.type == 20" ref="duoxuan" :type="form.type" />
      <panduan v-else-if="form.type == 30" ref="panduan" :type="form.type" />
      <tiankong v-else-if="form.type == 40" ref="tiankong" :type="form.type" />
    </template>
    <div class="dialog-footer" style="text-align:center;">
      <el-button style="padding: 10px 30px;" @click="cancel()">取消</el-button>
      <el-button type="primary" @click="state==='create'?createData():updateData()">保存</el-button>
    </div>
  </div>
</template>
<script>
import { insert, update, get, getDictByCode } from '@/views/skill/course/api/exercises'
import Danxuan from '@/views/skill/course/components/Danxuan'
import Duoxuan from '@/views/skill/course/components/Duoxuan'
import Panduan from '@/views/skill/course/components/Panduan'
import Tiankong from '@/views/skill/course/components/Tiankong'
import { mapGetters } from 'vuex'
export default {
  name: 'ExercisesManage',
  components: { Danxuan, Duoxuan, Panduan, Tiankong },
  data() {
    return {
      courseId: '',
      questionId: '',
      parentId: '',
      constituteScore: '', // 试卷组成如果统一分值则把数值默认写上
      state: 'create',
      loading: '',
      anliContent: '',
      form: {
        type: ''
      },
      rules: {
        type: [
          { required: true, message: '请选择试题类型', trigger: 'change' }
        ]
      },
      dict: {
        STLX: []
      },
      typeArr: [
        {
          type: '10',
          cName: 'danxuan'
        },
        {
          type: '20',
          cName: 'duoxuan'
        }, {
          type: '30',
          cName: 'panduan'
        }, {
          type: '40',
          cName: 'tiankong'
        }
      ],
      showMore: false,
      isShowMoreBtn: false,
      data: {}
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.courseId = this.$route.query.ci
    this.state = this.$route.query.i ? 'update' : 'create'
    this.parentId = this.$route.query.pai || ''
    if (this.parentId) {
      this.getAnliContent()
    }
    for (const i in this.dict) {
      this.getDict(i)
    }
  },
  methods: {
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = response.data.data[0].list
          if (code === 'STLX' && response.data.data[0].list.length > 0) {
            this.form.type = response.data.data[0].list[0].dictValue
            if (this.parentId) {
              this.dict['STLX'].splice(this.dict['STLX'].findIndex(item => item.dictValue == '60'), 1)
            }
          }
          if (this.state === 'update') {
            this.questionId = this.$route.query.i || ''
            this.getFormInfo(this.questionId)
          }
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    getFormInfo(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.1)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id }).then(res => {
          loading.close()
          this.form.type = res.data.data.questionType
          this.data = res.data.data
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    cancel() {
      this.$router.back()
    },
    createData() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const cName = this.typeArr.filter(item => {
            return item.type === this.form.type
          })[0].cName
          const postData = this.$refs[cName].getPostData()
          if (postData) {
            if (this.questionId) { postData['id'] = this.questionId }
            if (this.parentId) {
              postData['parentId'] = this.parentId
            }
            postData['questionType'] = this.form.type
            postData['subjectId'] = this.courseId
            this.loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.1)'
            })
            insert(postData).then(res => {
              this.loading.close()
              this.$message({
                title: '成功',
                message: '创建成功！',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.$router.back()
                }
              })
            }).catch(() => {
              this.loading.close()
            })
          }
        }
      })
    },
    updateData() {
      const cName = this.typeArr.filter(item => {
        return item.type === this.form.type
      })[0].cName
      const postData = this.$refs[cName].getPostData()
      if (postData) {
        if (this.questionId) { postData['id'] = this.questionId }
        if (this.parentId) {
          postData['parentId'] = this.parentId
        }
        postData['questionType'] = this.form.type
        postData['subjectId'] = this.courseId
        this.loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.1)'
        })
        update(postData).then(res => {
          this.loading.close()
          this.$message({
            title: '成功',
            message: '修改成功！',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.$router.back()
            }
          })
        }).catch(() => {
          this.loading.close()
        })
      }
    },
    getAnliContent() {
      get({ id: this.parentId }).then(res => {
        this.anliContent = res.data.data.stem
        this.$nextTick(() => {
          if (this.$refs.anlicontent.clientHeight > 27) {
            this.isShowMoreBtn = true
          } else {
            this.isShowMoreBtn = false
          }
        })
      }).catch(() => {

      })
    }
  }
}
</script>
<style lang="scss" type="text/scss">
  $dark_gray: #bfced6;
  .question-manage {
    width: 100%;
    background-color: #fff;
    padding: 10px;
    .el-card__body {
      display: flex;
      line-height: 1.5;
      .title {
        font-size: 18px;
        font-weight: bold;
      }
      .ailicontent {
        display: flex;
        align-items: center;
      }
      .show-more-btn {
        flex: 0 0 60px;
        text-align: center;
        color: $mainColor;
        cursor: pointer;
      }
    }
    .main-title {
      position: relative;
      height: 40px;
      line-height: 40px;
      padding: 0 20px;
      background-color: #ffffff;
      border-bottom: 1px solid #e5e5e5;
      font-family: PingFangSC-Medium;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
      font-size: 14px;
      margin-bottom: 10px;
      &:before {
        content: "";
        position: absolute;
        width: 2px;
        @include bg-color($mainColor);
        top: 13px;
        bottom: 13px;
        left: 15px;
      }
    }
    .dataForm {
      width: 70%;
      margin: 20px auto 0;
      &.nomt {
        margin-top: 0;
      }
    }
  }
</style>
